package com.dszq.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dszq.article.mapper.ApArticleConfigMapper;
import com.dszq.article.mapper.ApArticleContentMapper;
import com.dszq.article.mapper.ApArticleMapper;
import com.dszq.article.service.ApArticleService;
import com.dszq.article.service.ArticleFreemarkerService;
import com.dszq.article.service.HotArticleService;
import com.dszq.common.constants.ArticleConstants;
import com.dszq.common.constants.BehaviorConstants;
import com.dszq.common.redis.CacheService;
import com.dszq.model.article.dtos.ArticleDto;
import com.dszq.model.article.dtos.ArticleHomeDto;
import com.dszq.model.article.dtos.ArticleInfoDto;
import com.dszq.model.article.mess.ArticleVisitStreamMess;
import com.dszq.model.article.pojos.ApArticle;
import com.dszq.model.article.pojos.ApArticleConfig;
import com.dszq.model.article.pojos.ApArticleContent;
import com.dszq.model.article.vos.HotArticleVo;
import com.dszq.model.common.dtos.ResponseResult;
import com.dszq.model.common.enums.AppHttpCodeEnum;
import com.dszq.model.user.pojos.ApUser;
import com.dszq.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/4/17 16:24]
 */
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 根据参数加载文章列表
     *
     * @param loadType       1为加载更多  2为加载最新
     * @param articleHomeDto
     * @return
     */
    @Override
    public ResponseResult load(Short loadType, ArticleHomeDto articleHomeDto) {
        //1.校验参数
        Integer size = articleHomeDto.getSize();
        if (size == null || size == 0)
        {
            size =10;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        articleHomeDto.setSize(size);
        //类型参数检验
        if(!loadType.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadType.equals(ArticleConstants.LOADTYPE_LOAD_NEW))
        {
            loadType = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if (StringUtils.isEmpty(articleHomeDto.getTag()))
        {
            articleHomeDto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间校验
        if(articleHomeDto.getMaxBehotTime() == null)
            articleHomeDto.setMaxBehotTime(new Date());
        if(articleHomeDto.getMinBehotTime() == null)
            articleHomeDto.setMinBehotTime(new Date());
        //2.查询数据
        List<ApArticle> articles = apArticleMapper.loadArticle(articleHomeDto,loadType);
        //3.结果封装
        ResponseResult responseResult = ResponseResult.okResult(articles);
        return responseResult;
    }
    @Autowired
    private ApArticleConfigMapper articleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;
    /**
     * 保存文章的方法
     *
     * @param articleDto 文章数据传输对象，包含文章的全部或部分信息
     * @return ResponseResult 返回一个结果对象，通常包含操作是否成功、错误信息等
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        if (articleDto == null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle =new ApArticle();
        BeanUtils.copyProperties(articleDto,apArticle);
        //2.判断是否存在id
        if (apArticle.getId()==null)
        {
            //2.1 不存在id  保存  文章  文章配置  文章内容
            save(apArticle);
            //文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            articleConfigMapper.insert(apArticleConfig);
            //文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //2.2 存在id   修改  文章  文章内容

            //修改  文章
            updateById(apArticle);
            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(apArticleContent);

        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle,articleDto.getContent());
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 删除文章
     *
     * @param id 文章的唯一标识符
     * @return 返回操作结果，包括操作是否成功、错误信息等
     */
    @Override
    public ResponseResult deleteArticle(Long id) {
        apArticleMapper.deleteById(id);
        articleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,id));
        apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,id));
        return null;
    }
    @Autowired
    private CacheService cacheService;
    /**
     * 提交文章行为数据并加载相关分析结果。
     *
     * @param articleInfoDto 文章信息数据传输对象，包含文章的详细行为数据。
     * @return 返回操作结果，包括操作是否成功、错误信息等。
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto articleInfoDto) {
        //0.检查参数
        if (articleInfoDto == null || articleInfoDto.getArticleId() == null || articleInfoDto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;
        ApUser user = AppThreadLocalUtil.getUser();
        if(user!=null)
        {
            //like
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleInfoDto.getArticleId(), user.getId().toString());
            if (StringUtils.isNotBlank(likeBehaviorJson))
            {
                islike = true;
            }
            //unlike
            String unlikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleInfoDto.getArticleId(), user.getId().toString());
            if (StringUtils.isNotBlank(unlikeBehaviorJson))
            {
                isunlike = true;
            }
            //collection
            String collectionBehaviorJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), articleInfoDto.getArticleId().toString());
            if (StringUtils.isNotBlank(collectionBehaviorJson))
            {
                iscollection = true;
            }
            //follow
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), articleInfoDto.getAuthorId().toString());
            System.out.println(score);
            if(score != null){
                isfollow = true;
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if (firstPage)
        {
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr))
            {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(type,dto);
    }
    @Autowired
    private HotArticleServiceImpl hotArticleServiceImpl;
    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;
        //3.替换当前文章对应频道的热点数据
        replaceHotDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ apArticle.getChannelId());
        //4.替换推荐首页对应的热点数据
        replaceHotDataToRedis(apArticle,score,ArticleConstants.DEFAULT_TAG + ArticleConstants.DEFAULT_TAG);
    }

    public void replaceHotDataToRedis(ApArticle apArticle, Integer score,String key) {
        String string = cacheService.get(key);
        if (StringUtils.isNotBlank(string))
        {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(string, HotArticleVo.class);
            boolean flag = true;
            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }
                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(key, JSON.toJSONString(hotArticleVoList));
        }
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null?0:apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;
    }
    /**
     * 计算文章的具体分值。根据文章的点赞数、浏览数、评论数和收藏数，按照预设权重计算文章的分值。
     *
     * @param apArticle 文章对象
     * @return 文章的热度分数
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer scere = 0;
        // 根据点赞数、浏览数、评论数和收藏数计算分值
        if(apArticle.getLikes() != null){
            scere += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            scere += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            scere += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            scere += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return scere;
    }
}
